package com.sunyard.constant.msg;


import com.sunyard.utils.msg.PropertyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author daox.nie
 * @created 2016年12月8日 上午8:44:25
 * @description 配置文件内容缓存
 */
public class ConfCache {
    /**
     * Description
     */
    private static volatile HashMap<String, String> CONF_CACHE;

    /**
     * Description
     */
    public static final String CONF_FILE_NAME = "conf.properties";

    /**
     * Description
     */
    private static final Logger logger = LoggerFactory.getLogger(ConfCache.class);

    /**
     * Description
     */
    private synchronized static void init() {
        if (CONF_CACHE == null || CONF_CACHE.isEmpty()) {
            CONF_CACHE = new HashMap<>();
            logger.info("ConfCache start to load " + CONF_FILE_NAME);
            Properties p = PropertyUtil.getProperties(CONF_FILE_NAME);
            Enumeration e = p.keys();
            while (e.hasMoreElements()) {
                String key = e.nextElement().toString();
                String value = p.get(key).toString();
                logger.debug("key:" + key + ",value:" + value + "\n");
                CONF_CACHE.put(key, value);
            }
        }
    }

    /**
     * Description
     */
    public static String getValue(String key) {
        return getValue(key, null);
    }

    /**
     * Description
     */
    public static String getValue(String key, String defaultVaule) {
        if (CONF_CACHE == null || CONF_CACHE.isEmpty()) {
            init();
        }
        String value = CONF_CACHE.get(key.trim());
        return value == null ? defaultVaule : value.trim();
    }
}
